﻿using MvvmOrm.Services;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using System.Linq;
using MvvmOrm.DbmsModules;
using MvvmOrm.Properties;
using System.IO;

namespace MvvmOrm.Tests
{
    [TestClass()]
    public class CodeCompilerTest
    {
        private TestContext testContextInstance;

        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        // 
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion

        [TestMethod()]
        public void CompileCodeTest()
        {
            Models.MainViewModel mainViewModel = Common.PrepareSqliteContext();
            mainViewModel.DB.OutputDirectory = Common.GetTemporaryDirectory();
            mainViewModel.DB.Namespace = "TestModels";
            SqliteModule target = SqliteModule.Instance;
            target.AnalyseDatabase(mainViewModel.DB);
            Dictionary<string, string> sources = target.GenerateCode(mainViewModel.DB);
            Assert.AreEqual(sources.Count, 12);

            DirectoryInfo directoryOutput = new DirectoryInfo(mainViewModel.DB.OutputDirectory);
            if (!directoryOutput.Exists)
                directoryOutput.Create();

            var results = MvvmOrm.Services.CodeCompiler.CompileCode(
                        sources.Values.Concat(new[] { Settings.Default.AssemblyInfo }).ToArray(),
                        target.AdditionalReferencedAssemblies,
                        Path.Combine(mainViewModel.DB.OutputDirectory, mainViewModel.DB.Namespace + ".dll"),
                        Settings.Default.GenerateXmlDoc ? Path.Combine(mainViewModel.DB.OutputDirectory, mainViewModel.DB.Namespace + ".xml") : null);
            Assert.AreEqual(results.Errors.Count, 0);
            Directory.Delete(mainViewModel.DB.OutputDirectory, true);
        }
    }
}
